import { createStore, Store, useStore as useVuexStore } from 'vuex'
import { IRootState } from './types'
import { IStoreType } from './types'
import loginModule from './vuex/login/login'
import systemModule from './vuex/main/system/system'
import dashboardModule from './vuex/main/analysis/dashboard'
import { getPageListData } from '@/service/main/system/system'

const store = createStore<IRootState>({
  state: () => {
    return {
      name: 'coderwhy',
      age: 18,
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  getters: {},
  mutations: {
    changeEntireDepartment(state, departmentList) {
      state.entireDepartment = departmentList
    },
    changeEntireRole(state, roleList) {
      state.entireRole = roleList
    },
    changeEntireMenu(state, entireMenu) {
      state.entireMenu = entireMenu
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // request data
      const departmentResult = await getPageListData('/department/list', {
        offset: 0,
        size: 10
      })
      const { list: departmentList } = departmentResult.data

      const roleResult = await getPageListData('/role/list', {
        offset: 0,
        size: 20
      })
      const { list: roleList } = roleResult.data

      const menuResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuResult.data
      // save data
      commit('changeEntireDepartment', departmentList)
      commit('changeEntireRole', roleList)
      commit('changeEntireMenu', menuList)
    }
  },
  modules: {
    loginModule,
    systemModule,
    dashboardModule
  }
})

//为了获取登录信息，派发全局的login中的数据，在main.ts中调用，获取最新vuex中的数据
export function setupStore() {
  store.dispatch('loginModule/loadLocalLogin')
  store.dispatch('getInitialDataAction')
}
//支持ts，对useStore做一个增强
export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
